var editFormComboBox = function(config) {
	return new Ext.form.ComboBox(Ext.apply({
	    displayField   : 'text',
	    valueField     : 'id',
	    typeAhead      : true,
	    triggerAction  : 'all',
	    selectOnFocus  : true,
	    editable       : false,
	    listeners      : {
	    	change : function(field, newValue, oldValue ) {
				var form = this.findParentByType('form', true);
				if(form) {
					form.hasChanged = true;
				}
			}
	    },
	    store: new Ext.data.JsonStore({
	        url        : config.url,
	        baseParams : {
	        	node : config.nodeId
	        },
	        fields     : [
	             {
	               name : 'text',
	               mapping: 'text'
	             },
	             {
	               name : 'id',
	               mapping : 'id'
	             },
	             {
	               name : 'dep',
	               mapping : 'department'
	             }
	        ],
	        autoLoad   : true,
			listeners  : {
				load  : function() {
					var combo = Ext.getCmp(config.id);
					combo.setValue(config.value);
				},
				scope : this
			}
	    })
	}, config));
}

var buildDepartmentEditForm = function(responseJson) {
	var departmentEditForm = formPanel();
	
	var Name  = textField({id:'name', fieldLabel:'Name', allowBlank:true});
	Name.setValue(responseJson.name);
	
	var Email = textField({id:'email', fieldLabel:'Email', allowBlank:true});
	Email.setValue(responseJson.email);
	
	var Phone = textField({id:'phone', fieldLabel:'Phone', allowBlank:true});
	Phone.setValue(responseJson.phone);
	
	departmentEditForm.add(Name);
	departmentEditForm.add(Email);
	departmentEditForm.add(Phone);
	
	return departmentEditForm;
}

var buildProjectEditForm = function(responseJson) {
	var projectEditForm = formPanel();
	
	var Name = textField({id:'name', fieldLabel:'Name', allowBlank:true});
	Name.setValue(responseJson.name);
	
	var Email = textField({id:'email', fieldLabel:'Email', allowBlank:true});
	Email.setValue(responseJson.email);
	
	var Phone = textField({id:'phone', fieldLabel:'Phone', allowBlank:true});
	Phone.setValue(responseJson.phone);
	
	var Department = editFormComboBox({
		id         : 'departmentComboBox',
		fieldLabel : 'Department',
		hiddenName : 'department',
		emptyText  : 'Choose department ...',
		url        : 'dispatcher/getAllList',
		nodeId     : '_DEP_',
		value      : responseJson.departmentId
	});
	
	projectEditForm.add(Name);
	projectEditForm.add(Email);
	projectEditForm.add(Phone);
	projectEditForm.add(Department);
	
	return projectEditForm;
}

var buildEmployeeEditForm = function(responseJson) {
	var employeeEditForm = formPanel();
	
	var Name = textField({id:'name', fieldLabel:'Name', allowBlank:true});
	Name.setValue(responseJson.name);
	
	var BirthDate = dateField({id:'birthDate', fieldLabel:'Birth date', allowBlank:false});	
	BirthDate.setValue(new Date(responseJson.birthDate));
	
	var Email = textField({id:'email', fieldLabel:'Email', allowBlank:true});
	Email.setValue(responseJson.email);
	
	var Phone = textField({id:'phone', fieldLabel:'Phone', allowBlank:true});	
	Phone.setValue(responseJson.phone);
	
	var HiredDate = dateField({id:'hiredDate', fieldLabel:'Hired date', allowBlank:false});
	HiredDate.setValue(new Date(responseJson.hiredDate));
	
	var Position = positionComboBox();
	Position.setValue(responseJson.position);
	
	var tpl = new Ext.XTemplate(
			'<tpl for="."><div class="x-combo-list-item">',
				'<div>{text}</div>',
				'<div class="combo-list-department">Department: {dep}</div>',
			'</div></tpl>'
	);
	tpl.compile();
	
	var Project = editFormComboBox({
		id         : 'projectComboBox',
		fieldLabel : 'Project',
		hiddenName : 'project',
		emptyText  : 'Choose project ...',
		url        : 'dispatcher/getAllList',
		nodeId     : '_PRJ_',
		value      : responseJson.projectId,
		tpl        : tpl,
		itemSelector: 'div.x-combo-list-item'
	});
	
	employeeEditForm.add(Name);
	employeeEditForm.add(BirthDate);
	employeeEditForm.add(Email);
	employeeEditForm.add(Phone);
	employeeEditForm.add(HiredDate);
	employeeEditForm.add(Position);
	employeeEditForm.add(Project);
	
	return employeeEditForm;
}

var createEditForm = function(selNode, treePanelObj) {	
	Ext.Ajax.request({
		url    : 'dispatcher/getElement',
		
		params : {
			node     : selNode.id,
			nodeName : selNode.text
		},
		
		success: function(response, opts) {
			var responseJson = Ext.util.JSON.decode(response.responseText);

			if (responseJson.success == "true") {
				
				var selNodePath = selNode.getPath();
				
				if (selNode.id.match('_DEP_')) {
					var form = buildDepartmentEditForm(responseJson);
					var wTitle = "Edit Department";
				}
				else if (selNode.id.match('_PRJ_')) { 
					var form = buildProjectEditForm(responseJson);
					var wTitle = "Edit Project";
				}
				else if (selNode.id.match('_EMP_')) {
					var form = buildEmployeeEditForm(responseJson);
					var wTitle = "Edit Employee";
				}
											
			    var window = new Ext.Window({
			    	title  : wTitle,
			    	width  : 400,
			    	layout : 'fit',
			        plain:true,
			        bodyStyle:'padding:5px;',
			        buttonAlign:'center',
			        items: form,

			        buttons: [{
			        	text: 'Update',
			        	handler: function() {
			        		if(form.hasChanged) {
				        		form.getForm().submit({
				        			url : 'dispatcher/updateElement',
				        			params : {
				        				node           : selNode.id,
				        				parentNodeName : (selNode.parentNode) ?  selNode.parentNode.text : null
				        			},
				        			waitTitle: 'Please wait...',
				        			waitMsg: 'Wait...',
				        			success: function(form, action) {
				        				var result = action.result;
				        				if(result.success === 'true') {
				        					window.close();	                	
				            				root = treePanelObj.getRootNode();
				            				root.reload();
				            				treePanelObj.expandPath(selNodePath);
				        				} else {
				        					processErrors(result);
				        				}
				        			},
				        			failure: function(form, action) {
				        				switch (action.failureType) {
				        				case Ext.form.Action.CLIENT_INVALID:
				        	                Ext.Msg.alert('ERROR', 'Form fields may not be submitted with invalid values');
				        	                break;
				        	            case Ext.form.Action.CONNECT_FAILURE:
				        	                Ext.Msg.alert('ERROR', 'Ajax communication failed');
				        	                break;
				        	            case Ext.form.Action.SERVER_INVALID:
				        	            	Ext.Msg.alert('ERROR', 'An error occured with the server.\n' + action.result);
				        				}
				        			}
				        		});
			        		}
			        	}
			        }]
			    });

			    window.show();
			} else {
				Ext.Msg.alert('ERROR', 'An error occured during data retrieving on the server. ' + (responseJson.errorMessage ? responseJson.errorMessage : ''));
			}
		}
	});
};